/**
 * User: Do
 * Date: 11/25/13
 * Time: 9:02 AM
 */
function changeLitmitValue(obj){
    var obj = $(obj);
    if (obj.val() == '500'){
        obj.val('1000');
    }
    else if (obj.val() == '1000'){
        obj.val('5000');
    }
    else{
        obj.val('500');
    }
}
// Jquery
$(function () {
    shortcut.add("ctrl+1", function() {
        var lbMessage = document.getElementById('lbMessage');
        var message = document.getElementById('message');
        message.checked = true;
        setReportType(lbMessage);
    });
    shortcut.add("ctrl+2", function() {
        var lbLead = document.getElementById('lbLead');
        var lead = document.getElementById('lead');
        lead.checked = true;
        setReportType(lbLead);
    });
    shortcut.add("ctrl+3", function() {
        var lbTrend = document.getElementById('lbTrend');
        var trend = document.getElementById('trend');
        trend.checked = true;
        setReportType(lbTrend);
    });
    shortcut.add("ctrl+4", function() {
        var lbSOV = document.getElementById('lbSOV');
        var sov = document.getElementById('sov');
        sov.checked = true;
        setReportType(lbSOV);
    });
    shortcut.add("ctrl+5", function() {
        var lbSMT = document.getElementById('lbSMT');
        var smt = document.getElementById('smt');
        smt.checked = true;
        setReportType(lbSMT);
    });
    shortcut.add("ctrl+6", function() {
        var lbAuthor = document.getElementById('lbAuthor');
        var author = document.getElementById('author');
        author.checked = true;
        setReportType(lbAuthor);
    });
    shortcut.add("ctrl+7", function() {
        var lbThread = document.getElementById('lbThread');
        var thread = document.getElementById('thread');
        thread.checked = true;
        setReportType(lbThread);
    });
    shortcut.add("ctrl+8", function() {
        var lbSource = document.getElementById('lbSource');
        var source = document.getElementById('source');
        source.checked = true;
        setReportType(lbSource);
    });

    //Focus hand cursor end textbox or textarea
    $.fn.focusToEnd = function() {
        return this.each(function() {
            var v = $(this).val();
            $(this).focus().val("").val(v);
        });
    };
    //event tab query
    $(".list input").bind("keydown", "tab", function() {
        editor  = $('.query');

    });
    //multi query
    $(".report-type input").change(function(){
        $.cookie("index-query",0);
    });
    var number = $('.list input').size();
    if(number == 1){
        $($('.list').find('span').get(0)).hide();
    }
    //add query
    $("label").inFieldLabels();
    var add_query = $('#add_query');
    add_query.keypress(function(event){
        var keycode = (event.keyCode ? event.keyCode : event.which);
        if(keycode == 13){
            var query_name = document.getElementById('add_query').value;
            if(query_name != ""){
                addQuery(query_name);
                document.getElementById('add_query').value = "";
            }
        }
    });
    var add_p_lable = $('#add p label');
    var add_query_text = $('#add_query_text');
    add_query.focus(function(){
        add_p_lable.text("Your query here!");
        add_query_text.show();
    });
    add_query.focusout(function(){
        add_p_lable.text("+ New query:");
        add_query_text.hide();
        var query_name = document.getElementById('add_query').value;
        if(query_name != ""){
            addQuery(query_name);
            document.getElementById('add_query').value = "";
        }
    });

});
// Function Javascript multi query
function tabChange(e, obj){
    var TABKEY = 9;
    e = e|| window.event;
    var keycode;
    if (window.event){
        keycode = e.which ? window.event.which : window.event.keyCode;
    }
    if(e.which == TABKEY){
        obj = $(obj);
        list        = $('.list-query');
        editor       = $('.query');
        index   = obj.parent().index();
        find    = editor.find('textarea');
        setTimeout(function(){
            $(find.get(index)).focusToEnd();
        },10)
    }
}
function tabChangeTextarea(e, obj){
    var TABKEY = 9;
    e = e|| window.event;
    var keycode;
    if (window.event){
        keycode = e.which ? window.event.which : window.event.keyCode;
    }
    if(e.which == TABKEY){
        obj = $(obj);
        list        = $('.list');
        editor       = $('.query');
        index   = obj.parent().index();
        find    = list.find('input');
        setTimeout(function(){
            findTextarea    = editor.find('textarea');
            var num = findTextarea.size();
            if(index<num-1){
                editor.find('li').hide();
                $('.root').parent().show();
                //Show query index
                $(editor.find('li').get(index+1)).show();
                $(editor.find('li').get(index+1)).find('textarea').show();
                $(list.find('input').get(index)).css("width","215px");
                $(list.find('input').get(index+1)).css("width","216px");
                $(find.get(index+1)).focusToEnd();
            }else if(index == num-1){
                $('#add_query').focus();
            }
        },10)
    }
}
function tabAddChange(e, obj){
    var TABKEY = 9;
    e = e|| window.event;
    var keycode;
    if (window.event){
        keycode = e.which ? window.event.which : window.event.keyCode;
    }
    if(e.which == TABKEY){
        obj = $(obj);
        list    = $('.list');
        find    = list.find('input');
        editor  = $('.query');
        findTextarea    = editor.find('textarea');
        if(obj.val()==""){
            setTimeout(function(){
                editor.find('li').hide();
                //Show query index
                $(editor.find('li').get(0)).show();
                $(list.find('input')).css("width","215px");
                $(list.find('input').get(0)).css("width","216px");
                $(find.get(0)).focusToEnd();
            },10)
        }else{
            var num = findTextarea.size();
            setTimeout(function(){
                $(editor.find('textarea').get(num)).focusToEnd();
            },10)
        }

    }
}
function setReportType(obj){
    $('.report-type label').removeClass('active');
    obj = $(obj);
    obj.addClass('active');

    type = obj.attr('id');

    querytree   = $('.query-tree');
    list        = $('.list-query');
    query       = $('.query');
    query_add   = $('#add_query_text');
    //Set multiple query
    if (type == 'lbTrend' || type == 'lbSOV'){
        list.removeClass('hidden');
        query.css("left","650px");
        query_add.css("left","650px");
        list.css("left","430px");
    }
    else{
        query.css("left","450px");
        query_add.css("left","450px");
        list.css("left","230px");
        list.addClass('hidden');
        find    = query.find('li');
        find.hide();
        //Always show root query textarea
        root = $('.root');
        root.parent().show();
        root.show();
    }
}
var count       = 1;
var max         = 10;
var num         = 1;
function removeQuery(obj){
    var number = $('.list input').size();
    if(number == 1){
    }else{
        num--;
        count--;
        obj     = $(obj);
        list    = $('.list');
        editor  = $('.query');
        index   = obj.parent().index();
        find    = editor.find('textarea');
        remove = editor.find('p');
        if(index == 0){
            $(find.get(1)).addClass('root').attr('id','query').attr('name','query[]').css('display','block');
        }
        list.find('li').get(index).remove();
        editor.find('li').get(index).remove();
        $.cookie("index-query",index-1);
        editor.find('li').hide();
        $('.root').parent().show();
        $(editor.find('li').get(index-1)).show();

        $(list.find('input')).css("width","215px").css("background","#fdfdfd").css("color","#939393").css("border-right", "1px solid #cccccc");
        $(list.find('input').get(index-1)).css("width","216px").css("background","white").css("color","#606060").css("border-right", "none");
        number = $('.list input').size();
        if(number == 1){
            $(list.find('span').get(0)).hide();
        }
        var numberTextArea = $('.query textarea').size();
        //tabindex
        for(var i =0; i<number; i++){
            $('.list input:eq('+i+')').attr('tabindex',2*i+1);
        }
        for(var j =0; j<numberTextArea; j++){
            $('.query textarea:eq('+j+')').attr('tabindex',2*j+2);
        }
        $('#add_query').attr('tabindex',number*2+1);
    }
}

function showQuery(obj){
    obj     = $(obj);
    list    = $('.list');
    editor  = $('.query');
    index   = obj.parent().index();
    indexView = index;
    find    = editor.find('textarea');
    remove = editor.find('p');
    editor.find('li').hide();
    //Always show root query textarea
    $('.root').parent().show();
    //Show query index
    $(editor.find('li').get(index)).show();
    $(editor.find('li').get(index)).find('textarea').show();
    //index query
    $.cookie("index-query",index);
    $(list.find('input')).css("width","215px").css("background","#fdfdfd").css("color","#939393").css("border-right", "1px solid #cccccc");
    $(list.find('input').get(index)).css("width","216px").css("background","white").css("color","#606060").css("border-right", "none");

}
function focusInput(obj){
    obj     = $(obj);
    list    = $('.list');
    index   = obj.parent().index();
    showQuery(obj);
    $(list.find('input').get(index)).focus();
}
function show_Query(index, content){
    editor  = $('.query');
    indexView = index;
    find    = editor.find('textarea');
    remove = editor.find('p');
    editor.find('li').hide();
    //Always show root query textarea
    $('.root').parent().show();
    //Show query index
    $(find.get(index)).val(content);
    $(editor.find('li').get(index)).show();
    $(editor.find('li').get(index)).find('textarea').show();
}
function addQuery(query){
    if (num == max){
        alert('You only create ' + max + ' queries');
        return;
    }
    list    = $('.list');
    editor  = $('.query');
    $.cookie("index-query",count);
    num++;
    count++;
    list.append('<li><span class="delete" onclick="removeQuery(this)"><img src="views/public/images/manager-del.png"></span><input onclick="showQuery(this)" onkeydown="tabChange(event, this)" name="query-name[]" type="text" value="'+query+'" autocomplete="off"><p onclick="focusInput(this)">:</p></li>');
    editor.find('ul').append('<li><textarea onmouseover="showRemoveContent(this)" onkeyup="showRemoveContent(this)" onkeydown="tabChangeTextarea(event, this)" value="Query ' + (count) + '" name="query[]" placeholder="Your query here!"></textarea><p class="remove-content" onclick="removeContent(this)"  hidden="hidden"><img src="views/public/images/manager-del.png"></p></li>');
    $(list.find('input')).css("width","215px").css("background","#fdfdfd").css("color","#939393").css("border-right", "1px solid #cccccc");
    $(list.find('input').get(count-1)).css("width","216px").css("background","white").css("color","#606060").css("border-right", "none");
    var number = $('.list input').size();
    if(number > 1){
        $(list.find('span').get(0)).show();
    }
    //tabindex
    var numberTextArea = $('.query textarea').size();
    for(var i =0; i<number; i++){
        $('.list input:eq('+i+')').attr('tabindex',2*i+1);
    }
    for(var j =0; j<numberTextArea; j++){
        $('.query textarea:eq('+j+')').attr('tabindex',2*j+2);
    }
    $('#add_query').attr('tabindex',number*2+1);
}
function add_Query(query, content){
    if (num == max){
        alert('You only create ' + max + ' queries');
        return;
    }
    list    = $('.list');
    editor  = $('.query');
    $.cookie("index-query",count);
    num++;
    count++;
    list.append('<li><span class="delete" onclick="removeQuery(this)"><img src="views/public/images/manager-del.png"></span><input onclick="showQuery(this)"  onkeydown="tabChange(event, this)" name="query-name[]" type="text" value="'+query+'"><p onclick="focusInput(this)">:</p></li>');
    editor.find('ul').append('<li><textarea onmouseover="showRemoveContent(this)" onkeyup="showRemoveContent(this)" onkeydown="tabChangeTextarea(event, this)" name="query[]">' + content + '</textarea><p class="remove-content" onclick="removeContent(this)"  hidden="hidden"><img src="views/public/images/manager-del.png"></p></li>');
    $(list.find('input')).css("width","215px").css("background","#fdfdfd").css("color","#939393").css("border-right", "1px solid #cccccc");
    $(list.find('input').get(count-1)).css("width","216px").css("background","white").css("color","#606060").css("border-right", "none").focus();
    var number = $('.list input').size();
    if(number > 1){
        $(list.find('span').get(0)).show();
    }
}
function removeContent(obj){
    obj = $(obj);
    obj.parent().find('textarea').val("");
    obj.parent().find('p').hide('1000');
}
function showRemoveContent(obj){
    obj = $(obj);
    var content = obj.val();
    if(content != ""){
        obj.parent().find('p').show();
    }else{
        obj.parent().find('p').hide();
    }
}

/**
 * Close download dialog
 * @param obj
 */
function closeDownloadDialog(obj){
    frame = $(obj).parent().parent();
    frame.fadeOut(300);
    frame.find('iframe').attr('src', null);
}

function showDownloadDialog(obj){
    frame = $(obj).parent().parent().parent().find(".download-frame").fadeIn(300);
}

// Save Report
function showReportName(obj){
    obj = $(obj);
    obj.parent().find("#SaveReportName").show();
}
function closeSaveReport(obj){
    obj = $(obj);
    obj.parent().parent().find("#SaveReportName").hide();
}
function saveReport(type){
    //var parent = $("#tabs-"+index).find('.toolbar').find('form');
    //var qname = $('#SaveReportTextName').val();
    //var query = parent.find('#total-number').val();
    var duration = "";
    var smt = "";
    var language = "";
    var report_type = "";
    $.ajax({
        type: "POST",
        dataType: "json",
        data:{},
        before:(function(){

        }),
        success:(function(){

        }),
        error:(function(){

        })

    });
}

$(document).bind('click', function (e) {
    var $clicked = $(e.target);
    if (!$clicked.parents().hasClass("download-content") && ($clicked.parent().find('.download-frame').css('display')=='block'))
    {
        obj = $clicked.parent().find('.download-content').find('span');
        frameDownload = $clicked.parent().find('#download-frame-dialog');
        downloaded = frameDownload.contents().find('#loadingSpan');
        if(downloaded.hasClass('downloaded')){
            closeDownloadDialog(obj);
        }else{
            showComfirm("Close Download Dialog", obj);
        }

    }
    //hide context menu query tree
    if(!$clicked.parent().hasClass('tree_contextmenu')){
        $("#tree_contextmenu").hide();
    }
});


function showComfirm(note, obj){
    $.confirm({
        'title'		: note,
        'message'	: 'You are about to close download. <br />Your data has not been downloaded! Continue?',
        'buttons'	: {
            'Yes'	: {
                'class'	: 'blue',
                'action': function(){
                    closeDownloadDialog(obj);
                }
            },
            'No'	: {
                'class'	: 'gray',
                'action': function(){}
            }
        }
    });
}

/**
 * Laguage, smt filter
 */
$(window).on('load', function () {
    selectpicker = $('.smt-select');
    selectpicker.selectpicker({
        'selectedText': 'cat',
        showIcon:true
    });
    selectpicker.selectpicker('selectAll');

    //Language
    language_select = $('.language-select');
    language_select.selectpicker({
        'selectedText': 'cat',
        showIcon:true
    });

    //Get cookie
    try{
        var language = $.cookie('language');
        var langValue = convertArray(language);
        language_select.selectpicker('val', langValue);
    }catch (err){}
    //if not select language filter, smt still do
    try{
        var smt = $.cookie('smtfilter');
        var smtValue = convertArray(smt);
        selectpicker.selectpicker('val', smtValue);
    }catch(err){}

});
function convertArray(string){
    var result = new Array();
    var num = 0;
    var str = "";
    for(var i =0; i<string.length; i++){
        if(string[i] == "," || i == string.length-1){
            if(i == string.length-1){
                result[num] = str + string[string.length-1];
            }else{
                result[num] = str;
            }
            str = "";
            num++;
        }else{
            str = str + string[i];
        }
    }
    return result;
}

//Jquery
$(function(){
    // event change content textare
    var root = $('.root');
    root.val($.cookie("query"));
    root.bind('input propertychange', function() {
        var query = document.getElementById("query").value;
        $("#save_tab").css("opacity", 1);
        document.getElementById('save_tab').disabled = false;
        $.cookie("query",query);
    });

    //Context menu tree query
    tree_contextmenu = $("#tree_contextmenu");
    tree = $('#tree');
    createGroup = $('#create_group');
    createQuery = $('#create_query');

    tree.bind('contextmenu', function(e){
        e.preventDefault();
        var $clicked = $(e.target);
        if(!$clicked.hasClass('jstree-clicked')){

            xOffset = 245;
            yOffset = 100;
            tree_contextmenu
                .show()
                .css("top",(e.pageY - xOffset) + "px")
                .css("left",(e.pageX - yOffset) + "px");
        }else{
            tree_contextmenu.hide();
        }
    });
    createGroup.click(function(e){
        var nodeID = "";
        try{
            var parent_node = $.jstree._reference('#tree')._get_parent();
            nodeID = parent_node.attr("id");

        }catch(e){
            nodeID = "node_2";
        }

        $("#tree").jstree("create", "#"+nodeID, "last", { "attr" : { "rel" : "folder" } });
    });
    createQuery.click(function(e){
        var nodeID = "";
        try{
            var parent_node = $.jstree._reference('#tree')._get_parent();
            nodeID = parent_node.attr("id");
        }catch (e){
            nodeID = "node_2";
        }
        $("#tree").jstree("create", "#"+nodeID, "last", { "attr" : { "rel" : "default" } });
    });
    /**Remove content textarea*/
    $('.query').mouseleave(function(){
        $('.query').find('li').find('p').hide();
    });

});

